package com.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Date: 2024/6/5 23:11
 * Author: T_log
 * Description: BarrierDemo
 */
public class BarrierDemo {

    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);

        client.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("收到一个zookeeper的事件");
            }
        });

        client.start();
        System.out.println("success connected.....");


        DistributedDoubleBarrier doubleBarrier = new DistributedDoubleBarrier(client,"/narrier/double",10);
        // 每台机器都会阻塞在enter这里
        doubleBarrier.enter();

        // 直到10台机器都调用了enter，结汇从enter这里往下走

        // 这个功能可以做一些计算任务

        // 每台机器都会在阻塞在leave这里，直到10台机器都调用了leave
        doubleBarrier.leave();
    }
}
